/**
*	@file	hcomms.h
*	@author	Artur Gilmutdinov <arturg000@gmail.com>
*	@brief	Contains hcomm_srv_t naming server for distributed objects.
*/


#pragma once
#include <cstdio>
#include <vector>
#include <map>
#include "hsock.h"
#include "common.h"

#define log log_t::log

using namespace std;

class obj_rec_t
{
	public:
	char *name;
	char *pass;
	
	obj_rec_t(char *name, char *pass)
	{
		this->name = new char [255];
		this->pass = new char [255];
		strcpy(this->name, name);
		if (pass!=NULL)
		strcpy(this->pass, pass);
		else this->pass = NULL;
	}
};

/*
*	@class	node_t
*	@brief	Meta information about nodes that handle distributed objects.
*/
class node_t
{
	public:
	char ip[255];	
	int port;		// node port
	char name[255];
	int status;
	vector<obj_rec_t*> object;
	bool check();
};

class portrange_t
{
	public:
	int begin;
	int end;
};

/*
*	@class	hcomm_srv_t
*	@brief	Naming server for objects.
*/
class hcomm_srv_t
{
	vector<node_t*>  node;
	portrange_t cliports;	// new
	
//	Sends object's ip to clients. Called by serve.
	void serve_ifs(int socket);
	
//	Add node name and it's ip to table.
	void addnode(int socket, char *ip);
	
//	Add record about object to table.
	void addobj(int socket);
	
	public:

//	Start listening clients. 
	void start(int srvport, int cb, int ce)
	{
		cliports.begin = cb;
		cliports.end = ce;
		hsock_t sock;
		sock.server<hcomm_srv_t>(this, srvport);	
	}
	
	// called by hsock. Serve comm clients. 
	void serve(int socket, char *ip, int port)
	{
		char bf[255];
		recv(socket, bf, 255, 0);
		log("comm:");
		log(bf);
		log("cliport: ");
		char bf1[255];
		sprintf(bf1, "%d", port);
		log(bf1);
		if (!strcmp(bf,"ifs\n"))
			serve_ifs(socket);	
		else if (!strcmp(bf,"addnode\n"))
			addnode(socket, ip);
		else if (!strcmp(bf,"addobj\n"))
			addobj(socket);
	}
};
